<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<style>
  .layui-table-cell {
    overflow: visible;
  }
  
  .layui-table-box {
    overflow: visible;
  }
  
  .layui-table-body {
    overflow: visible;
  }
  
  /* 设置下拉框的高度与表格单元相同 */
  td .layui-form-select {
    margin-top: -10px;
    margin-left: -15px;
    margin-right: -15px;
  }
  
  .fieldTable {
    padding-left: 10px;
    padding-right: 10px;
  }
  
  div[class*="editor-"] {
    position: absolute;
    width: 98%;
    height: 80vh;
  }
  
  .prevTabContent {
    padding: 0;
  }
  
  .layui-table-cell {
    height: 100%;
    max-width: 100%;
  }
</style>
<div class="layui-row">
  <div class="layui-col-md4 fieldTable">
    <fieldset class="layui-elem-field layui-field-title">
      <legend>默认配置</legend>
    </fieldset>
    <table
      class="layui-hide"
      id="fieldTable"
      lay-filter="fieldTableFilter"></table>
  </div>
  <div class="layui-col-md8 fieldTable">
    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px">
      <span class="layui-badge layui-bg-gray">ctrl</span>+<span class="layui-badge layui-bg-gray">alt</span>+<span class="layui-badge layui-bg-gray">h</span> 呼出快捷键提示
    </blockquote>
    <form class="patchForm layui-form">
      相对路径：
      <div class="layui-inline">
        <input style="width: 500px" class="layui-input" type="text" id="filePath" name="filePath" placeholder="如： src/main/java/controller">
      </div>
      文件后缀：
      <div class="layui-inline">
        <input class="layui-input" type="text" id="fileType" name="fileType" placeholder="如： java | html | xml">
      </div>
      <input type="hidden" id="currentTab" value="">
      <div class="layui-btn-group">
        <button type="button" class="layui-btn layui-btn-normal" id="saveTemplate">保存
        </button>
        <button type="button" class="layui-btn" id="deleteTemplate">删除
        </button>
      </div>
    </form>
    
    <div class="layui-layout-admin">
      <div class="layui-icon admin-tabs-control layui-icon-prev" id="leftPage"></div>
      <div
        id="templateTab"
        class="layui-tab layui-tab-card"
        lay-filter="fileTabFilter"
        lay-allowClose="true">
        <ul class="layui-tab-title">
        </ul>
        <div class="layui-tab-content prevTabContent">
        </div>
      </div>
      <div class="layui-icon admin-tabs-control layui-icon-next" id="rightPage"></div>
    </div>
  </div>
</div>
<script src="/util/utils.js"></script>

<script
  type="text/html"
  id="fieldTableToolbar">
  <div class="layui-btn-group">
    <button
      type="button"
      class="layui-btn layui-btn-sm"
      id="addFileTab"
      lay-event="addFileTab">
      添加模版
    </button>
  </div>
</script>

<script
  type="text/html"
  id="customTableToolbar">
  <div class="layui-btn-group ">
    <button
      type="button"
      class="layui-btn layui-btn-xs"
      lay-event="addCustom">
      添加字段
    </button>
    <button
      type="button"
      class="layui-btn layui-btn-xs layui-btn-normal"
      lay-event="saveCustom">
      保存
    </button>
  </div>
</script>

<script
  src="/ace/ace.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/theme-merbivore.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/theme-twilight.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/theme-tomorrow.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/mode-html.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/mode-javascript.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/mode-typescript.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/mode-java.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/mode-xml.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/ext-language_tools.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/ext-beautify.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/ext-prompt.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/ext-settings_menu.js"
  type="text/javascript"
  charset="utf-8"></script>
<script
  src="/ace/ext-keybinding_menu.js"
  type="text/javascript"
  charset="utf-8"></script>

<script th:inline="javascript">
  ace.require('ace/ext/language_tools')
  ace.require('ace/ext/beautify')
  ace.require('ace/ext/settings_menu')
  ace.require('ace/ext/prompt')
  ace.require('ace/ext/static_highlight')

  var templateId = [[${templateId}]]
  var defaultOptions = [[${defaultOptions}]]
  var filePathMap = {}
  var fileTypeMap = {}
  

  layui.use(['form', 'table', 'element', 'admin'], function () {
    var $ = layui.$,
      table = layui.table,
      form = layui.form,
      admin = layui.admin,
      element = layui.element,
      fieldTableData = defaultOptions.map(item => {
        return {
          fieldKey: item.value,
          fieldValue: item.label,
          example: item.example
        }
      })

    form.render()

    var tableInit = table.render({
      id: 'fieldTable',
      elem: '#fieldTable',
      toolbar: '#fieldTableToolbar',
      defaultToolbar: [''],
      page: false,
      limit: Number.MAX_VALUE,
      cols: [
        [
          {
            field: 'fieldKey',
            title: '模版内名称',
            edit: false,
            width: '30%'
          },
          {
            field: 'fieldValue',
            title: '对应名称',
            width: '30%'
          },
          {
            field: 'example',
            title: '例子',
            templet: function (d) {
              if (isJsonString(d.example)) {
                return Object.keys(JSON.parse(d.example)).map(item => {
                  return '<div>' + item + ':' + JSON.parse(d.example)[item] + '</div>'
                }).join('')
              } else {
                return d.example || ''
              }
            }
          }
        ]
      ],
      data: fieldTableData
    })

    var defaultData = []

    getListData()
    initTabs()

    function getListData() {
      $.get('/code/template/field/list', {templateId: templateId}, function (response) {
        defaultData = response.data
        var resultData = fieldTableData.concat(defaultData)
        tableInit.reload({
          data: resultData
        })
      })
    }

    function initTabs() {
      filePathMap = {}
      fileTypeMap = {}
      var currentTab = $('#currentTab').val()
      $('.templates').length > 0 && $('.templates').each((index, item) => {
        var editorId = $(item).data('editor-id')
        element.tabDelete('fileTabFilter', editorId)
      })

      $.get('/code/template/file/list', {templateId: templateId}, function (response) {
        response.data.forEach(item => {
          var id = item.id,
            data = item.file
          var fileName = item.fileName
          var forId = fileName.replace('.', '-')
          var options = {
            title: '<span class="title">' + fileName + '</span>',
            content: '<div data-id="' + id + '" data-editor-id="' + forId + '" class="templates editor-' + forId + '" id="' + forId + '_editor"></div>', //支持传入html
            id: forId
          }
          filePathMap[forId] = item.filePath
          fileTypeMap[forId] = item.fileType
          element.tabAdd('fileTabFilter', options)
          renderEditor(options.id, data)
          tableInit.resize()
        })
        element.tabChange('fileTabFilter', currentTab || response.data[0].fileName.replace('.', '-'))
      })
    }

    function addTab(value) {
      if (value) {
        var forId = value.replace('.', '-')
        var options = {
          title: '<span class="title">' + value + '</span>',
          content: '<div data-id="" data-editor-id="' + forId + '" class="templates editor-' + forId + '" id="' + forId + '_editor"></div>', //支持传入html
          id: forId
        }
        filePathMap[forId] = ''
        fileTypeMap[forId] = value.split('.')[1]
        element.tabAdd('fileTabFilter', options)
        element.tabChange('fileTabFilter', options.id)
        renderEditor(options.id, value)
        tableInit.resize()
        layer.close(layer.index)
      }
    }

    function renderEditor(id, data) {
      var type = fileTypeMap[id]
      if (type === 'js') {
        type = 'javascript'
      }
      if (type === 'ts') {
        type = 'typescript'
      }
      if (type === 'vue') {
        type = 'javascript'
      }
      var editor = ace.edit(id + '_editor', {
        wrap: false,
        fontSize: '14px',
        autoScrollEditorIntoView: true,
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
        showPrintMargin: '120'
      })
      editor.setTheme('ace/theme/merbivore')
      editor.session.setMode('ace/mode/' + type)
      editor.session.setValue(data)

      // add command to lazy-load keybinding_menu extension
      editor.commands.addCommand({
        name: 'showKeyboardShortcuts',
        bindKey: {
          win: 'Ctrl-Alt-h',
          mac: 'Command-Alt-h'
        },
        exec: function (editor) {
          ace.config.loadModule('ace/ext/keybinding_menu', function (module) {
            module.init(editor)
            editor.showKeyboardShortcuts()
          })
        }
      })
    }

    //监听头工具栏事件
    table.on('toolbar(fieldTableFilter)', function (obj) {
      var checkStatus = table.checkStatus(obj.config.id),
        data = checkStatus.data //获取选中的数据
      switch (obj.event) {
        case 'addFileTab':
          layer.prompt({
            formType: 0,
            value: '', //初始时的值，默认空字符
            maxlength: 20,
            title: '请输入模版名（带后缀）',
            area: ['800px', '350px'], //自定义文本域宽高
            success: function () {
              $('input.layui-layer-input').on('keydown', function (e) {
                if (e.which === 13) {
                  addTab(e.target.value)
                }
              })
            }
          }, function (value, index, elem) {
            addTab(value)
          })
          break
        case 'saveCustom':
          $.ajaxSetup({
            traditional: true,
            contentType: 'application/json;charset=utf-8'
          })

          //向服务端发送删除指令
          $.post('/code/template/field', JSON.stringify(obj.config.data), function (response) {
            layer.msg(response.data, {
              time: 1000,
              icon: 1
            })
            getListData()
          })
          break
        case 'delete':
          if (data.length === 0) {
            layer.msg('请选择一行')
          } else {
          }
          break
      }
    })

    $('#deleteTemplate').on('click', function () {
      var currentTab = $('#currentTab').val().replace('-', '.')
      if (currentTab) {
        $.ajax({
          url: '/code/template/file/' + templateId + '/' + currentTab,
          type: 'DELETE',
          success: function (response) {
            if (response.data) {
              layer.msg(response.data, {
                time: 1000,
                icon: 1
              })
              element.tabDelete('fileTabFilter', currentTab.replace('.', '-'))
            }
          }
        })
      }
    })

    element.on('tab(fileTabFilter)', function (data) {
      var fileName = $(this).attr('lay-id')
      $('#currentTab').val(fileName)
      $('#filePath').val(filePathMap[fileName])
      $('#fileType').val(fileTypeMap[fileName])
    })

    $('#filePath').on('input', function (e) {
      //获取input输入的值
      var fileName = $('#templateTab .layui-tab-title .layui-this').attr('lay-id')
      filePathMap[fileName] = e.delegateTarget.value
    })

    $('#fileType').on('input', function (e) {
      //获取input输入的值
      var fileName = $('#templateTab .layui-tab-title .layui-this').attr('lay-id')
      fileTypeMap[fileName] = e.delegateTarget.value
    })

    function saveTemplate() {
      var data = [],
        count = 0,
        countType = 0

      $('.templates').length > 0 && $('.templates').each((index, item) => {
        var editorId = $(item).data('editor-id')
        var id = $(item).data('id')
        var content = ace.edit(editorId + '_editor').getValue()
        if (!filePathMap[editorId]) {
          count++
        }
        if (!fileTypeMap[editorId]) {
          countType++
        }
        data.push({
          id: id,
          templateId: templateId,
          fileName: editorId.replace('-', '.'),
          filePath: filePathMap[editorId],
          fileType: fileTypeMap[editorId],
          file: encodeURIComponent(content)
        })
      })

      if (count > 0) {
        layer.msg('存在未设置的路径，请检查', {
          time: 2000,
          icon: 2
        })
        return false
      } else if (countType > 0) {
        layer.msg('存在未设置的后缀名，请检查', {
          time: 2000,
          icon: 2
        })
        return false
      } else {
        $.ajaxSetup({
          traditional: true,
          contentType: 'application/json;charset=utf-8'
        })

        $.post('/code/template/file', JSON.stringify(data), function (response) {
          // layer.closeAll('page')
          layer.msg(response.data, {
            time: 1000,
            icon: 1
          })
          initTabs()
        }, 'json')
      }
    }

    $('#saveTemplate').on('click', function () {
      saveTemplate()
    })

    document.onkeydown = function (e) {
      var keyCode = e.key
      var ctrlKey = e.ctrlKey || e.metaKey
      if (ctrlKey && ['S', 's'].includes(keyCode)) {
        saveTemplate()
        e.preventDefault()
      }
    }

    function scrollerTab(length) {
      $('#templateTab .layui-tab-title').animate({scrollLeft: length}, 'fast')
    }

    $('#leftPage').on('click', (e) => {
      scrollerTab('-=400')
    })

    $('#rightPage').on('click', (e) => {
      scrollerTab('+=400')
    })
    
  })

</script>
</html>
